<template>
  <el-card class="admin-card" shadow="hover">
    <div class="admin-header">
      <h3>{{ admin.username }}</h3>
      <el-tag type="info">{{ admin.region || "No Region" }}</el-tag>
    </div>
    <el-divider></el-divider>
    <el-row :gutter="10">
      <el-col :span="12">
        <label><strong>ID:</strong></label>
        <el-input v-model="admin.userId" disabled></el-input>
      </el-col>
      <el-col :span="12">
        <label><strong>Password:</strong></label>
        <el-input v-model="admin.password" show-password></el-input>
      </el-col>
      <el-col :span="12">
        <label><strong>Email:</strong></label>
        <el-input v-model="admin.email"></el-input>
      </el-col>
      <el-col :span="12">
        <label><strong>Phone:</strong></label>
        <el-input v-model="admin.phone"></el-input>
      </el-col>

      <el-col :span="12">
        <label><strong>Region:</strong></label>
        <el-input v-model="admin.region"></el-input>
      </el-col>
      <el-col :span="12">
        <label><strong>Username:</strong></label>
        <el-input v-model="admin.username"></el-input>
      </el-col>

      <el-col :span="12">
        <label><strong>Birth:</strong></label>
        <el-date-picker v-model="admin.birth" type="date" placeholder="Select birth date"></el-date-picker>
      </el-col>
      <el-col :span="12">
        <label><strong>Job:</strong></label>
        <el-input v-model="admin.job"></el-input>
      </el-col>
    </el-row>
    <template #footer>
      <el-button type="primary" @click="saveEdit">保存</el-button>
    </template>
  </el-card>
</template>

<script setup lang="ts">
import { defineProps, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import instance from "@/utils/http";
import { useAuthStore } from "@/stores/auth";
import { useRouter } from "vue-router";

type Admin = {
  userId: number,
  username: string,
  region: string,
  phone: string,
  password: string,
  job: string,
  points: number,
  email: string,
  birth: string,
}

const admin = ref<Admin>({
  userId: 0,
  username: "",
  region: "",
  phone: "",
  password: "",
  job: "",
  points: 0,
  email: "",
  birth: "",
});

const router = useRouter();

onMounted(() => {
  instance.get("/auth/user/profile").then(res => {
    if (res.data.code === 404) {
      localStorage.clear();
      useAuthStore().clearToken();
      router.go(0);
    } else {
      admin.value = res.data.data;
    }
  });
});

// Save edited field
const saveEdit = () => {
  instance.put(`/user/${admin.value.userId}`, admin.value)
    .then(() => {
      ElMessage.success('Changes saved successfully');
    })
    .catch(() => {
      ElMessage.error('Failed to save changes');
    });
};
</script>

<style scoped>
.admin-card {
  width: 100%;
  margin-bottom: 20px;
}

.admin-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.actions {
  display: flex;
  justify-content: flex-end;
}
</style>
